package com.dong.thread.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semaphore 信号量
 *
 * @author by jiweidong on 2021/11/28.
 */
public class T07_Semaphore {

    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(1);
//        Semaphore semaphore = new Semaphore(2);
//        Semaphore semaphore = new Semaphore(1, true); // 可以公平锁

        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("T1 running...");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("T1 running...");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("T2 running...");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("T2 running...");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}
